// utils/websocket/socket.js

import routeWebSocketMessage from './router';

let socket = null;
let currentUserId = null; // 当前连接的 userId

function connectSocket(userId) {
  if (socket && currentUserId === userId) {
    console.log('已经连接到该用户，无需重复连接');
    return;
  }

  // 如果是其他用户先断开旧连接
  if (socket) {
    closeSocket();
  }

  const wsUrl = `ws://192.168.1.109:9007/ws/userId:${userId}`;

  socket = uni.connectSocket({
    url: wsUrl,
    success: () => console.log('WebSocket 连接创建成功')
  });

  socket.onOpen(() => {
    console.log('WebSocket 已连接');
    socket.send({ data: JSON.stringify({ type: 'auth', sid: userId }) });
  });

  socket.onMessage(res => {
    try {
      const msg = JSON.parse(res.data);
      routeWebSocketMessage(msg); // 分发消息
    } catch (e) {
      console.error('解析消息失败:', res.data);
    }
  });

  socket.onError(err => {
    console.error('WebSocket 错误:', err);
  });

  socket.onClose(() => {
    console.log('WebSocket 已关闭');
    socket = null;
    currentUserId = null;
  });

  currentUserId = userId;
}

function closeSocket() {
  if (socket) {
    socket.close();
    socket = null;
    currentUserId = null;
  }
}

export default {
  connectSocket,
  closeSocket
};